const express = require('express');
const router = express.Router();
const db = require('../database')

router.get('/stafflist',(req, res) => {
    let currentPage = req.query.currentPage  //当前页
    let pageSize = parseInt(req.query.pageSize)// 页大小
    let start = (currentPage -1)*pageSize;
    let sql = db.stafflistByPage(start,pageSize);
    console.log(currentPage,pageSize)
  console.log(sql)
    db.query(sql).then(data => {
      // console.log(data)
        // 查询总页数 一起返回
        db.query(db.stafflistTotalNum()).then(data2 => {
          const total = data2[0].total;
          res.send({"code": "200", "message": "查询成功！", "data":data,'total':total});
        })
    },err => {
      res.send({"code": "401", "message": "查询失败"});
    })
})

router.get('/allStafflist',(req, res) => {
  let sql = db.stafflist();
  db.query(sql).then(data => {
      res.send({"code": "200", "message": "查询成功！", "data":data});
  },err => {
    res.send({"code": "401", "message": "查询失败"});
  })
})

router.post('/addStaff',(req, res) => {
  let staffForm = req.body.form;
  console.log(staffForm)
  let sql = db.addStaff(staffForm);
  console.log(sql)
  db.query(sql).then(data => {
    console.log(data)
    res.send({"code": "200", "message": "添加成功！"});
  },err => {
    res.send({"code": "401", "message": "添加失败"});
  })
})

router.post('/updateStaff',(req, res) => {
  let id = req.body.id;
  let staffForm = req.body.form;
  let sql = db.updateStaff(id,staffForm);
  console.log(sql)
  db.query(sql).then(data => {
    console.log(data)
    res.send({"code": "200", "message": "修改成功！"});
  },err => {
    res.send({"code": "401", "message": "修改失败"});
  })
})

router.post('/findStaffById',(req, res) => {
  let id = parseInt(req.body.id);
  let sql = db.findStaffById(id);
  console.log(sql)
  db.query(sql).then(data => {
    res.send({"code": "200", "message": "查找成功！",'data':data});
  },err => {
    res.send({"code": "401", "message": "查找失败"});
  })
})
router.post('/deleteStaffById',(req, res) => {
  let id = parseInt(req.body.id);
  let sql = db.deleteStaffById(id);
  console.log(sql)
  db.query(sql).then(data => {
    res.send({"code": "200", "message": "删除成功！"});
  },err => {
    res.send({"code": "401", "message": "删除失败"});
  })
})

router.post('/findStaffByName', (req, res) => {
  let name = req.body.name;
  let sql = db.findStaffByName(name);
  db.query(sql).then(data => {
    res.send({"code": "200", "message": "查找成功！",'data':data});
  },err => {
    res.send({"code": "401", "message": "查找失败"});
  })
})

router.post('/queryStaffPresenceInfoByMonth', (req, res) => {
  let MonthForm = req.body.MonthForm;
  let id = req.body.id? req.body.id : 1;
  let sql = MonthForm.length === 0? db.queryStaffPresenceInfoById(id) : db.queryStaffPresenceInfoByMonthAndId(MonthForm,id);
  db.query(sql).then(data => {
    res.send({"code": "200", "message": "查找成功！",'data':data});
  },err => {
    res.send({"code": "401", "message": "查找失败"});
  })
})
module.exports = router